/**
 * 
 */
package kr.pe.johnkim.dayve.rest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import kr.pe.johnkim.dayve.provider.DayveItem;
import kr.pe.johnkim.dayve.util.ExternalJoinConstant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * @author johnkim
 *
 */
public class DayveItemRest {
	public static final String TAG = DayveItemRest.class.getSimpleName();

	// 서버 주소.
	public static final String SERVER_URL = ExternalJoinConstant.MOBILE_SERVER_URL;

	// 컨트롤러 매핑.
	public static final String MYHISTORY_ITEM_CONTROLLER = "/myHistoryItemController";

	// Item 중복 검사.
	public static final String MYHISTORY_ITEM_CHECK_DUPLICATION = "/checkDuplication";
	
	// Item 을 등록 한다.
	public static final String MYHISTORY_ITEM_REGISTER = "/registerItem";
	
	// Item 목록을 가져 온다.
	public static final String MYHISTORY_ITEM_LIST = "/selectItemList";
	
	// Item 내용을 가져 온다.
	public static final String MYHISTORY_ITEM = "/selectItem";
	
	// Item 을 수정 한다.
	public static final String MYHISTGORY_ITEM_UPDATE = "/updateItem";
	
	// Item 을 비활성화 한다.
	public static final String MYHISTORY_ITEM_DEACTIVATE = "/updateDeactivateItem";
	
	/**
	 * 카테고리 등록 시 이름으로 중복 검사를 한다.
	 * 
	 * 등록되어 있는 카테고리 이름의 갯수를 가져 온다.
	 * 
	 * 1. 카테고리 이름이 등록되어 있지 않으면 : 0
	 * 2. 카테고리 이름이 이미 등록되어 있으면 : 1
	 * 3. 실행 중 오류 발생     : ERROR
	 * 
	 * @param dayveItem
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveItem checkDuplication(DayveItem dayveItem) throws JSONException, IOException {
		Log.i(TAG, "checkDuplication");
		
		JSONObject jsonItem = new JSONObject();
		
		jsonItem.put("name", dayveItem.getName());
		jsonItem.put("activateYn", dayveItem.getActivateYn());
		jsonItem.put("myHistoryMembersId", dayveItem.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryItem\":" + jsonItem.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveItem mDayveItem = new DayveItem();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_CONTROLLER + MYHISTORY_ITEM_CHECK_DUPLICATION);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonItem = new JSONObject(line);
	            	JSONObject mJsonItem2 = mJsonItem.getJSONObject("myHistoryItem");
	            	
	            	mDayveItem.setCount(mJsonItem2.getString("count"));
	        	}
	        }
	        
	        Log.i(TAG, "Success to check duplication item.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to check duplicatiotn item.");
		}
		
		return mDayveItem;
		
	}
	
	/**
	 * Item 을 등록 한다.
	 * 
	 * @param dayveItem
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveItem registerItem(DayveItem dayveItem) throws JSONException, IOException {
		Log.i(TAG, "registerItem");
		
		JSONObject jsonItem = new JSONObject();
		
		jsonItem.put("name", dayveItem.getName());
		jsonItem.put("comment", dayveItem.getComment());
		jsonItem.put("amount", dayveItem.getAmount());
		jsonItem.put("openItemYn", dayveItem.getOpenItemYn());
		jsonItem.put("favoriteYn", dayveItem.getFavoriteYn());
		jsonItem.put("activateYn", dayveItem.getActivateYn());
		jsonItem.put("modifyDate", dayveItem.getModifyDate());
		jsonItem.put("registerDate", dayveItem.getRegisterDate());
		jsonItem.put("myHistoryMembersId", dayveItem.getMyHistoryMembersId());
		jsonItem.put("myHistoryCategoriesIdMyHistoryCategories", dayveItem.getMyHistoryCategoriesIdMyHistoryCategories());
		
		String jsonString = "{\"myHistoryItem\":" + jsonItem.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveItem mDayveItem = new DayveItem();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_CONTROLLER + MYHISTORY_ITEM_REGISTER);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonGroup = new JSONObject(line);
	            	JSONObject mJsonGroup2 = mJsonGroup.getJSONObject("myHistoryItem");
	            	
	            	// SUCCESS or FAIL
	            	mDayveItem.setResult(mJsonGroup2.getString("result"));
	        	}
	        }
	        
	        Log.i(TAG, "Success to register item.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to register item.");
		}
		
		return mDayveItem;
	}
	
	/**
	 * Item 목록을 가져 온다.
	 * 
	 * @param dayveItem
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public ArrayList<DayveItem> selectItemList(DayveItem dayveItem) throws JSONException, IOException {
		Log.i(TAG, "selectItemList");
		
		JSONObject jsonItem = new JSONObject();		
		
		jsonItem.put("activateYn", dayveItem.getActivateYn());
		jsonItem.put("myHistoryMembersId", dayveItem.getMyHistoryMembersId());
		jsonItem.put("itemStart", dayveItem.getItemStart());
		jsonItem.put("itemCount", dayveItem.getItemCount());
		
		String jsonString = "{\"myHistoryItem\":" + jsonItem.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		ArrayList<DayveItem> itemList = new ArrayList<DayveItem>();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_CONTROLLER + MYHISTORY_ITEM_LIST);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "postUrl : " + postUrl);
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONArray jsonArray = new JSONArray(line);
	            	
	            	Log.i(TAG, "jsonArray.length() : " + jsonArray.length());
	            	
	            	for(int i=0 ; i<jsonArray.length() ; i++) {
	            		JSONObject mJsonItem = jsonArray.getJSONObject(i);
		            	JSONObject mJsonItem2 = mJsonItem.getJSONObject("myHistoryItem");
		            	
		            	DayveItem mDayveItem = new DayveItem();
		            	
		            	mDayveItem.setIdMyHistoryItems(mJsonItem2.getString("idMyHistoryItems"));
		            	mDayveItem.setName(mJsonItem2.getString("name"));
		            	mDayveItem.setComment(mJsonItem2.getString("comment"));
		            	mDayveItem.setAmount(mJsonItem2.getString("amount"));
		            	mDayveItem.setOpenItemYn(mJsonItem2.getString("openItemYn"));
		            	mDayveItem.setFavoriteYn(mJsonItem2.getString("favoriteYn"));
		            	mDayveItem.setActivateYn(mJsonItem2.getString("activateYn"));
		            	mDayveItem.setModifyDate(mJsonItem2.getString("modifyDate"));
		            	mDayveItem.setRegisterDate(mJsonItem2.getString("registerDate"));
		            	mDayveItem.setMyHistoryMembersId(mJsonItem2.getString("myHistoryMembersId"));
		            	mDayveItem.setMyHistoryCategoriesIdMyHistoryCategories(mJsonItem2.getString("myHistoryCategoriesIdMyHistoryCategories"));
		            	
//		            	Log.i(TAG, "item name : " + mDayveItem.getName());
		            	
		            	itemList.add(mDayveItem);
	            	}
	        	}
	        }
	        
	        Log.i(TAG, "Success to select item list.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to select item list.");
		}
		
		return itemList;
	}
	
	/**
	 * Item 내용을 가져 온다.
	 * 
	 * @param dayveItem
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveItem selectItem(DayveItem dayveItem) throws JSONException, IOException {
		Log.i(TAG, "selectItem");
		
		JSONObject jsonItem = new JSONObject();

		jsonItem.put("idMyHistoryItems", dayveItem.getIdMyHistoryItems());
		jsonItem.put("activateYn", dayveItem.getActivateYn());
		jsonItem.put("myHistoryMembersId", dayveItem.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryItem\":" + jsonItem.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveItem mDayveItem = new DayveItem();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_CONTROLLER + MYHISTORY_ITEM);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonItem = new JSONObject(line);
	            	JSONObject mJsonItem2 = mJsonItem.getJSONObject("myHistoryItem");
	            	
	            	mDayveItem.setIdMyHistoryItems(mJsonItem2.getString("idMyHistoryItems"));
	            	mDayveItem.setName(mJsonItem2.getString("name"));
	            	mDayveItem.setComment(mJsonItem2.getString("comment"));
	            	mDayveItem.setOpenItemYn(mJsonItem2.getString("openItemYn"));
	            	mDayveItem.setFavoriteYn(mJsonItem2.getString("favoriteYn"));
	            	mDayveItem.setActivateYn(mJsonItem2.getString("activateYn"));
	            	mDayveItem.setModifyDate(mJsonItem2.getString("modifyDate"));
	            	mDayveItem.setRegisterDate(mJsonItem2.getString("registerDate"));
	            	mDayveItem.setMyHistoryMembersId(mJsonItem2.getString("myHistoryMembersId"));
	            	mDayveItem.setMyHistoryCategoriesIdMyHistoryCategories(mJsonItem2.getString("myHistoryCategoriesIdMyHistoryCategories"));
	        	}
	        }
	        
			Log.i(TAG, "Success to select item.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to select item.");
		}
		
		return mDayveItem;
	}
	
	/**
	 * Item 내용을 수정 한다.
	 * 
	 * @param dayveItem
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveItem updateItem(DayveItem dayveItem) throws JSONException, IOException {
		Log.i(TAG, "updateItem");
		
		JSONObject jsonItem = new JSONObject();
		
		jsonItem.put("idMyHistoryItems", dayveItem.getIdMyHistoryItems());
		jsonItem.put("name", dayveItem.getName());
		jsonItem.put("comment", dayveItem.getComment());
		jsonItem.put("amount", dayveItem.getAmount());
		jsonItem.put("openItemYn", dayveItem.getOpenItemYn());
		jsonItem.put("favoriteYn", dayveItem.getFavoriteYn());
		jsonItem.put("activateYn", dayveItem.getActivateYn());
		jsonItem.put("modifyDate", dayveItem.getModifyDate());
		jsonItem.put("myHistoryMembersId", dayveItem.getMyHistoryMembersId());
		jsonItem.put("myHistoryCategoriesIdMyHistoryCategories", dayveItem.getMyHistoryCategoriesIdMyHistoryCategories());
		
		String jsonString = "{\"myHistoryItem\":" + jsonItem.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveItem mDayveItem = new DayveItem();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_CONTROLLER + MYHISTGORY_ITEM_UPDATE);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonCategory = new JSONObject(line);
	            	JSONObject mJsonCategory2 = mJsonCategory.getJSONObject("myHistoryItem");
	            	
	            	// SUCCESS or FAIL
	            	mDayveItem.setResult(mJsonCategory2.getString("result"));
	        	}
	        }
	        
			Log.i(TAG, "Success to update item.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to update item.");
		}
		
		return mDayveItem;
	}

	/**
	 * Item 을 비활성화 한다.
	 * 
	 * @param dayveItem
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public DayveItem updateDeactivateItem(DayveItem dayveItem) throws JSONException, IOException {
		Log.i(TAG, "updateDeactivateItem");
		
		JSONObject jsonItem = new JSONObject();

		jsonItem.put("idMyHistoryItems", dayveItem.getIdMyHistoryItems());
		jsonItem.put("activateYn", dayveItem.getActivateYn());
		jsonItem.put("modifyDate", dayveItem.getModifyDate());
		jsonItem.put("myHistoryMembersId", dayveItem.getMyHistoryMembersId());
		
		String jsonString = "{\"myHistoryItem\":" + jsonItem.toString() + "}";
		
		Log.i(TAG, "jsonCategory : " + jsonString);
		
		DayveItem mDayveItem = new DayveItem();
		
		try {
			URL postUrl = new URL(SERVER_URL + MYHISTORY_ITEM_CONTROLLER + MYHISTORY_ITEM_DEACTIVATE);
			HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
	        connection.setDoOutput(true);
	        connection.setInstanceFollowRedirects(false);
	        connection.setRequestMethod("POST");
	        connection.setRequestProperty("Content-Type", "application/json");
	        OutputStream os = connection.getOutputStream();
	        os.write(jsonString.getBytes());
	        os.flush();
	        
	        Log.i(TAG, "response code : " + connection.getResponseCode());
	        
	        if(connection != null) {
	        	connection.setConnectTimeout(3000);
	        	
	        	if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	        		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            	
	            	String line = br.readLine();
	            	
	            	JSONObject mJsonCategory = new JSONObject(line);
	            	JSONObject mJsonCategory2 = mJsonCategory.getJSONObject("myHistoryItem");
	            	
	            	// SUCCESS or FAIL
	            	mDayveItem.setResult(mJsonCategory2.getString("result"));
	        	}
	        }
	        
			Log.i(TAG, "Success to deactivate item.");
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(TAG, "Fail to deactivate item.");
		}
		
		return mDayveItem;
	}
}
